package poland;

public class CompoundExpression extends Expression {
	private Expression _left;
	private Expression _right;

	public final static char[] Operators = { '+', '-', '*', '/', '^' };

	public static boolean isOperator(String str) {
		if (str.length() != 1)
			return false;

		char c = str.charAt(0);
		for (char op : Operators) {
			if (op == c)
				return true;
		}

		return false;
	}

	public CompoundExpression(String original, Expression left, Expression right) {
		super(original);
		_left = left;
		_right = right;
	}

	public char getOp() {
		return getOriginal().charAt(0);
	}

	public Expression getLeft() {
		return _left;
	}

	public void setLeft(Expression left) {
		_left = left;
	}

	public Expression getRight() {
		return _right;
	}

	public void setRight(Expression right) {
		_right = right;
	}

	@Override
	public double evaluate() {
		double l = _left.evaluate();
		double r = _right.evaluate();

		switch (getOp()) {
		case '+':
			return l + r;
		case '-':
			return l - r;
		case '*':
			return l * r;
		case '/':
			return l / r;
		case '^':
			return Math.pow(l, r);
		}

		throw new UnsupportedOperationException();
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		if (!isTopMost())
			sb.append("(");

		sb.append(_left.toString());
		sb.append(getOp());
		sb.append(_right.toString());

		if (!isTopMost())
			sb.append(")");

		return sb.toString();
	}
}
